<script setup lang="ts">
const route = useRoute()
const toast = useToast()
const { loggedIn } = useUserSession()

// 如果已经登录，重定向到首页
if (loggedIn.value) {
  await navigateTo('/')
}

const email = ref('')
const password = ref('')
const verificationCode = ref('')
const loginType = ref<'password' | 'code'>('password')
const loading = ref(false)
const error = ref('')
const codeSent = ref(false)
const countdown = ref(0)

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 发送验证码
async function sendCode() {
  if (!email.value) {
    error.value = '请输入邮箱地址'
    return
  }

  try {
    const response = await $fetch('/api/login/send', {
      method: 'POST',
      body: { email: email.value },
    })

    if (response.success) {
      toast.add({
        title: '验证码已发送',
        description: '请查收您的邮箱',
        icon: 'i-lucide-check-circle',
        color: 'success',
      })
      codeSent.value = true
      startCountdown()
    } else {
      error.value = response.statusMessage || '发送验证码失败'
    }
  } catch (err: any) {
    error.value = err.data?.statusMessage || '发送验证码失败，请检查网络连接'
  }
}

async function handleLogin() {
  if (!email.value) {
    error.value = '请输入邮箱地址'
    return
  }

  if (loginType.value === 'password' && !password.value) {
    error.value = '请输入密码'
    return
  }

  if (loginType.value === 'code' && !verificationCode.value) {
    error.value = '请输入验证码'
    return
  }

  loading.value = true
  error.value = ''

  if (loginType.value === 'password') {
    try {
      const response = await $fetch('/api/login/password', {
        method: 'POST',
        body: {
          email: email.value,
          password: password.value,
        },
      })

      if (response.success) {
        await useUserSession().fetch()
        toast.add({
          title: '登录成功',
          description: '欢迎回来！',
          icon: 'i-lucide-check-circle',
          color: 'success',
        })

        // 登录成功后跳转到首页
        await navigateTo('/')
      } else {
        error.value = response.statusMessage || '登录失败'
      }
    } catch (err: any) {
      error.value = err.data?.statusMessage || '登录失败，请检查网络连接'
    } finally {
      loading.value = false
    }
  }

  if (loginType.value === 'code') {
    try {
      const response = await $fetch('/api/login/verify', {
        method: 'POST',
        body: {
          email: email.value,
          code: verificationCode.value,
        },
      })

      if (response.success) {
        await useUserSession().fetch()
        toast.add({
          title: '登录成功',
          description: '欢迎回来！',
          icon: 'i-lucide-check-circle',
          color: 'success',
        })

        // 登录成功后跳转到首页
        await navigateTo('/')
      } else {
        error.value = response.statusMessage || '登录失败'
      }
    } catch (err: any) {
      error.value = err.data?.statusMessage || '登录失败，请检查网络连接'
    } finally {
      loading.value = false
    }
  }
}

function goToRegister() {
  navigateTo('/register')
}

function goToHome() {
  navigateTo('/')
}

// 设置页面元数据
useHead({
  title: '用户登录',
  meta: [{ name: 'description', content: '用户登录页面' }],
})
</script>

<template>
  <div
    class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900"
  >
    <div class="max-w-md w-full space-y-8">
      <!-- 头部 -->
      <div class="text-center">
        <NuxtLink
          to="/"
          class="inline-flex items-center gap-2 text-primary hover:text-primary-600 transition-colors"
        >
          <UIcon name="i-lucide-arrow-left" class="w-5 h-5" />
          <span>返回首页</span>
        </NuxtLink>
        <h2 class="mt-6 text-3xl font-extrabold text-gray-900 dark:text-white">
          用户登录
        </h2>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          请输入您的邮箱和密码或验证码进行登录
        </p>
      </div>

      <!-- 登录表单 -->
      <div
        class="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10"
      >
        <form class="space-y-6" @submit.prevent="handleLogin">
          <!-- 邮箱输入 -->
          <div>
            <label
              for="email"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              邮箱地址
            </label>
            <div class="mt-1">
              <input
                id="email"
                v-model="email"
                type="email"
                required
                class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入邮箱地址"
                :disabled="loading"
              />
            </div>
          </div>

          <!-- 登录方式切换 -->
          <div class="flex gap-2">
            <button
              type="button"
              :class="[
                'flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors',
                loginType === 'password'
                  ? 'bg-primary text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600',
              ]"
              @click="loginType = 'password'"
            >
              密码登录
            </button>
            <button
              type="button"
              :class="[
                'flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors',
                loginType === 'code'
                  ? 'bg-primary text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600',
              ]"
              @click="loginType = 'code'"
            >
              验证码登录
            </button>
          </div>

          <!-- 密码登录 -->
          <div v-if="loginType === 'password'">
            <label
              for="password"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              密码
            </label>
            <div class="mt-1">
              <input
                id="password"
                v-model="password"
                type="password"
                required
                class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入密码"
                :disabled="loading"
              />
            </div>
          </div>

          <!-- 验证码登录 -->
          <div v-if="loginType === 'code'">
            <label
              for="verificationCode"
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >
              验证码
            </label>
            <div class="mt-1 flex gap-2">
              <input
                id="verificationCode"
                v-model="verificationCode"
                type="text"
                required
                class="flex-1 appearance-none relative block px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white bg-white dark:bg-gray-700 rounded-md focus:outline-none focus:ring-primary focus:border-primary focus:z-10 sm:text-sm"
                placeholder="请输入验证码"
                :disabled="loading"
              />
              <button
                type="button"
                :disabled="loading || countdown > 0"
                class="px-4 py-2 text-sm font-medium text-white bg-primary rounded-md hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                @click="sendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
              </button>
            </div>
          </div>

          <!-- 错误提示 -->
          <div v-if="error" class="rounded-md bg-red-50 dark:bg-red-900/20 p-4">
            <div class="flex">
              <UIcon
                name="i-lucide-alert-circle"
                class="flex-shrink-0 h-5 w-5 text-red-400"
              />
              <div class="ml-3">
                <h3 class="text-sm font-medium text-red-800 dark:text-red-200">
                  {{ error }}
                </h3>
              </div>
            </div>
          </div>

          <!-- 登录按钮 -->
          <div>
            <button
              type="submit"
              :disabled="loading"
              class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <UIcon
                v-if="loading"
                name="i-lucide-loader-2"
                class="animate-spin -ml-1 mr-2 h-4 w-4"
              />
              {{ loading ? '登录中...' : '登录' }}
            </button>
          </div>

          <!-- 注册链接 -->
          <div class="text-center">
            <span class="text-sm text-gray-600 dark:text-gray-400"
              >还未注册？</span
            >
            <button
              type="button"
              class="text-sm text-primary hover:text-primary-600 underline ml-1 transition-colors"
              @click="goToRegister"
            >
              快速注册
            </button>
            <div class="mt-3">
              <NuxtLink
                to="/reset"
                class="text-sm text-gray-600 dark:text-gray-400 hover:text-primary underline"
              >
                忘记密码？
              </NuxtLink>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
